// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

#include "gtest/gtest.h"

#include "Utility/Stacktrace/SGSignal.h"

#include "DBManager/DBServiceFactory.h"
#include "DBManager/Database/DatabaseFactory.h"
#include "DBManager/Database/IDatabase.h"
#include "DBManager/UnitTest/HDF5/TestDB.h"

SG::DBManager::DBServiceFactory* DB::ServiceFactory = nullptr;
SG::DBManager::DatabaseFactory*  DB::DBFactory      = nullptr;

using SG::DBManager::IDatabase;

class Environment : public testing::Environment
{
  public:
    void SetUp () override
    {
        // 数据库工厂
        DB::DBFactory = new SG::DBManager::DatabaseFactory ();
        // 数据库
        IDatabase* db = DB::DBFactory->GetDatabase (SG::DBManager::DatabaseFactory::HDF5, ".", "DBManagerUnitTest.db");
        // 根据数据库创建Service管理器
        DB::ServiceFactory = new SG::DBManager::DBServiceFactory (db);
        DB::ServiceFactory->ClearDatabase ();
    }
    void TearDown () override
    {
        // 释放数据库资源
        delete DB::ServiceFactory;
        delete DB::DBFactory;
    }
};

#ifdef SG_USE_MPI
#include "Utility/Algebra/MpiEnvironment.h"
#endif

int main (int argc, char* argv[])
{
    SG::Utility::SGSignal::registerSignalHandlers ();

#ifdef SG_USE_MPI
    SG::Algebra::MpiEnvironment env (argc, argv);
#endif
    testing::AddGlobalTestEnvironment (new Environment ());
    testing::InitGoogleTest (&argc, argv);
    int result = RUN_ALL_TESTS ();

// 反初始化MPI
#ifdef SG_USE_MPI
    env.finalized ();
#endif
    return result;
}